//
//  DeviceSelectListViewController.m
//  FLORIDA
//
//  Created by 魏延(颜魏) on 2023/8/4.
//

#import "DeviceSelectListViewController.h"
#import "BTManager.h"
#import "GroupListViewController.h"
#import "CreatGroupViewController.h"
#import "BlutoothGroupModel.h"
#import "ProgressHUD.h"

@interface DeviceSelectListViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray<CBPeripheral *> *dataSource;
@property (nonatomic, strong) NSMutableArray<CBPeripheral *> *listData;

@end

@implementation DeviceSelectListViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadData) name:kBTBluGroupChanged object:nil];
    
    self.dataSource = [[NSMutableArray alloc] init];
    self.listData = [[NSMutableArray alloc] init];
    [self.dataSource addObjectsFromArray:[BTManager sharedBTManager].peripherals];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchDevices:) name:kBTSearchDevices object:nil];
    
    self.tableView.separatorInset = UIEdgeInsetsZero;
    self.tableView.separatorColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    
    [self reloadData];
}

- (void)reloadData {
    NSString *groupStr = [[NSUserDefaults standardUserDefaults] objectForKey:BatteryGroupBluList] ?: @"";
    [self.listData removeAllObjects];
    if (groupStr.length) {
        NSArray *dataArray = [BlutoothGroupModel jsonCovertToModel:groupStr];
        NSMutableArray *names = [NSMutableArray array];
        for (BlutoothGroupModel *model in dataArray) {
            for (NSInteger i=0; i<model.bluList.count; i++) {
                BlutoothModel *blu = model.bluList[i];
                [names addObject:blu.name];
            }
        }
        for (CBPeripheral *peripheral in self.dataSource) {
            if (![names containsObject:peripheral.name]) {
                [self.listData addObject:peripheral];
            }
        }
    }else {
        [self.listData addObjectsFromArray:self.dataSource];
    }
    [self.tableView reloadData];
}

- (IBAction)actionBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)actionShowMore:(NSInteger)index {
    UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"Set Group for battery" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    [sheet addAction:[UIAlertAction actionWithTitle:@"Select battery group" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        GroupListViewController *vc = [[GroupListViewController alloc] initWithNibName:@"GroupListViewController" bundle:nil];
        BlutoothModel *battery = [[BlutoothModel alloc] init];
        battery.name = self.listData[index].name;
//        battery.uuid = self.listData[index].identifier.description;
        vc.battery = battery;
        [self.navigationController pushViewController:vc animated:YES];
    }]];
    [sheet addAction:[UIAlertAction actionWithTitle:@"Creat battery group" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        CreatGroupViewController *vc = [[CreatGroupViewController alloc] initWithNibName:@"CreatGroupViewController" bundle:nil];
        BlutoothModel *model = [[BlutoothModel alloc] init];
        model.name = self.listData[index].name;
//        model.uuid = self.listData[index].identifier.description;
        vc.battery = model;
        vc.type = 0;
        [self.navigationController pushViewController:vc animated:YES];
    }]];
    [sheet addAction:[UIAlertAction actionWithTitle:@"Close" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:sheet animated:YES completion:nil];
}

#pragma mark - notification
- (void)searchDevices:(NSNotification *)nf {
    NSArray *list = nf.object;
    [self.dataSource removeAllObjects];
    [self.dataSource addObjectsFromArray:list];

    [self reloadData];
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    cell.backgroundColor = [UIColor clearColor];
    cell.contentView.backgroundColor = [UIColor clearColor];
    
    cell.imageView.image = [UIImage imageNamed:@"home_seg_1"];
    
    cell.textLabel.text = self.listData[indexPath.row].name;
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.font = [UIFont systemFontOfSize:18];
    
    UILabel *stateLabel = [[UILabel alloc] initWithFrame:CGRectMake(kWidth-100, 0, 90, 50)];
    stateLabel.font = [UIFont systemFontOfSize:14];
    stateLabel.textColor = [UIColor lightGrayColor];
    stateLabel.text = self.listData[indexPath.row].name == [BTManager sharedBTManager].peripheral.name ? @"Connected" : @"";
    [cell.contentView addSubview:stateLabel];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self actionShowMore:indexPath.row];
}


@end
